<template>
  <div class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-6 max-w-7xl">

      <!-- 查询条件区域 -->
      <el-card class="mb-6">
        <el-form ref="searchForm" :model="queryParams" label-width="80px">
          <!-- 第一行查询条件 -->
          <el-row :gutter="20" v-if="isExpanded || rowIndex === 0" :row-index="0" class="mb-4">
            <el-col v-if="showAccount" :span="6">
              <el-form-item label="账号:" label-width="60px">
                <el-input v-model="queryParams.account" placeholder="请输入账号" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="开具日期:" label-width="80px">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%;"
                  @change="handleDateRangeChange"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col v-if="showEntityName" :span="6">
              <el-form-item label="主体名称:" label-width="80px">
                <div class="flex items-center">
                  <el-input v-model="queryParams.productionEntity" placeholder="请输入主体名称" style="width: calc(100% - 80px);"></el-input>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="产品名称:" label-width="80px">
                <el-input v-model="queryParams.productName" placeholder="请输入产品名称" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行查询条件 - 省市区县乡镇 -->
          <el-row :gutter="20" v-if="isExpanded || currentRowIndex === 1" class="mb-4">
            <el-col v-if="showProvince" :span="6">
              <el-form-item label="省:" label-width="60px">
                <el-select v-model="queryParams.provinceCode" @change="onProvinceChange(false)" placeholder="请选择省" style="width: 100%;">
                  <el-option v-for="item in provinceList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col v-if="showCity" :span="6">
              <el-form-item label="市:" label-width="60px">
                <el-select v-model="queryParams.cityCode" @change="onCityChange(false)" :disabled="!queryCities.length" placeholder="请先选择省" style="width: 100%;">
                  <el-option v-for="city in queryCities" :key="city.code" :label="city.name" :value="city.code"></el-option>
                  <el-option v-if="!queryCities.length && queryParams.provinceCode" value="">暂无数据</el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col v-if="showDistrict" :span="6">
              <el-form-item label="区县:" label-width="60px">
                <el-select v-model="queryParams.districtCode" @change="onDistrictChange(false)" :disabled="!queryDistricts.length" placeholder="请先选择市" style="width: 100%;">
                  <el-option v-for="district in queryDistricts" :key="district.code" :label="district.name" :value="district.code"></el-option>
                  <el-option v-if="!queryDistricts.length && queryParams.cityCode" value="">暂无数据</el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col v-if="showTown && !isRegularUser" :span="6">
              <el-form-item label="乡镇/街道:" label-width="100px">
                <el-select
                  v-model="queryParams.townCode"
                  :disabled="!queryTowns.length"
                  placeholder="请先选择区县"
                  style="width: 100%;"
                  @change="onTownChange(false)"
                >
                <!-- 新增change事件 -->
                <el-option v-for="town in queryTowns" :key="town.code" :label="town.name" :value="town.code"></el-option>
                <el-option v-if="!queryTowns.length && queryParams.districtCode" value="">暂无数据</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第三行查询条件 -->
          <el-row :gutter="20" v-if="isExpanded || currentRowIndex === 2" class="mb-4">
            <el-col :span="6">
              <el-form-item label="检验机构:" label-width="80px">
                <div class="flex items-center">
                  <el-input v-model="queryParams.inspectionOrg" placeholder="请输入检验机构" style="width: calc(100% - 80px);"></el-input>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合格方式:" label-width="80px">
                <el-select v-model="queryParams.qualifiedMethod" placeholder="所有" style="width: 100%;">
                  <el-option label="委托检验" value="委托检验"></el-option>
                  <el-option label="监督抽检" value="监督抽检"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合格证编号:" label-width="100px">
                <el-input v-model="queryParams.certificateNo" placeholder="请输入合格证编号" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="数据来源:" label-width="80px">
                <el-select v-model="queryParams.dataSource" placeholder="请选择数据来源" style="width: 100%;">
                  <el-option label="平台录入" value="平台录入"></el-option>
                  <el-option label="API导入" value="API导入"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 查询按钮区域 -->
          <el-row :gutter="20" class="mb-4">
            <el-col :span="6">
              <el-form-item label="是否删除:" label-width="80px">
                <el-select v-model="queryParams.isDeleted" placeholder="请选择" style="width: 100%;">
                  <el-option label="未删除" value="0"></el-option>
                  <el-option label="已删除" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="18" class="flex items-center justify-start">
              <el-button type="primary" @click="getPage()" icon="el-icon-search">查询</el-button>
              <el-button @click="resetForm" icon="el-icon-refresh" class="ml-2">重置</el-button>
              <el-button @click="toggleExpand" class="ml-2" :icon="isExpanded ? 'el-icon-chevron-up' : 'el-icon-chevron-down'">
                {{ isExpanded ? '收起' : '展开' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form>

        <!-- 导出按钮 -->
        <el-row class="mb-4">
          <el-col>
            <el-button type="primary" @click="handleExport" icon="el-icon-download">导出</el-button>
            <el-button type="danger" @click="handleBatchOperation('delete')" icon="el-icon-delete" :disabled="selectedCount === 0">批量删除</el-button>
          </el-col>
        </el-row>

        <!-- 已选择条件 -->
        <el-row v-if="selectedCount > 0">
          <el-col>
            <div class="mt-4 p-3 bg-gray-50 rounded-md">
              <div class="text-sm text-gray-600 mb-2">已选择 {{ selectedCount }} 项</div>
              <el-button type="text" @click="clearSelected" class="text-sm">清空</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 表格区域 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-table
            ref="certificateTable"
            :data="tableData"
            style="width: 100%"
            border
            :fit="false"
            @selection-change="handleSelectionChange"
            :row-class-name="tableRowClassName"
            v-loading="tableLoading"
            element-loading-text="加载中..."
          >
            <!-- 复选框列 -->
            <el-table-column type="selection" width="55" align="center"></el-table-column>

            <!-- 基础信息列 -->
            <el-table-column prop="account" label="账号" align="center" min-width="100" v-if="showAccount"></el-table-column>
            <el-table-column prop="productionEntity" label="生产主体" align="center" min-width="180"></el-table-column>
            <el-table-column prop="legalPerson" label="法人姓名" align="center" min-width="100"></el-table-column>

            <!-- 地址信息列 -->
            <el-table-column prop="province" label="省" align="center" min-width="80" v-if="showProvince"></el-table-column>
            <el-table-column prop="city" label="市" align="center" min-width="80" v-if="showCity"></el-table-column>
            <el-table-column prop="district" label="区/县" align="center" min-width="80" v-if="showDistrict"></el-table-column>
            <el-table-column prop="town" label="镇/乡" align="center" min-width="100" v-if="showTown"></el-table-column>
            <el-table-column prop="companyAddress" label="公司地址" align="center" min-width="180"></el-table-column>
            <el-table-column prop="productionAddress" label="生产地址" align="center" min-width="180"></el-table-column>

            <!-- 产品信息列 -->
            <el-table-column prop="productName" label="产品名称" align="center" min-width="120"></el-table-column>
            <el-table-column label="产品数量" align="center" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.quantity || 0 }} {{ scope.row.unit || '无' }}
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedMethod" label="合格方式" align="center" min-width="120"></el-table-column>
            <el-table-column prop="inspectionOrg" label="检验机构" align="center" min-width="150"></el-table-column>

            <!-- 报告信息列 -->
            <el-table-column label="检测报告" align="center" min-width="150">
              <template slot-scope="scope">
                <el-link
                  @click="viewReport(scope.row.reportUrl)"
                  type="primary"
                  v-if="scope.row.reportName"
                >
                  {{ scope.row.reportName }} <i class="el-icon-document"></i>
                </el-link>
                <span v-else class="text-gray-400">无报告</span>
              </template>
            </el-table-column>

            <!-- 合格证信息列 -->
            <el-table-column
              prop="issueDate"
              label="开具日期"
              align="center"
              min-width="160"
              :formatter="formatTableDate"
            ></el-table-column>
            <el-table-column prop="certificateNo" label="合格证编号" align="center" min-width="180"></el-table-column>
            <el-table-column prop="printCount" label="打印次数" align="center" min-width="80"></el-table-column>
            <el-table-column prop="scanCount" label="扫描次数" align="center" min-width="80"></el-table-column>
            <el-table-column prop="dataSource" label="数据来源" align="center" min-width="120"></el-table-column>

            <!-- 状态列 -->
            <el-table-column prop="isDeleted" label="是否删除" align="center" min-width="100">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.isDeleted === 0">未删除</el-tag>
                <el-tag type="danger" v-else>已删除</el-tag>
              </template>
            </el-table-column>

            <!-- 系统信息列（按需显示） -->
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
              min-width="160"
              :formatter="formatTableDate"
              v-if="showSystemColumns"
            ></el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              align="center"
              min-width="160"
              :formatter="formatTableDate"
              v-if="showSystemColumns"
            ></el-table-column>
            <el-table-column
              prop="createUserId"
              label="创建人ID"
              align="center"
              min-width="100"
              v-if="showSystemColumns"
            ></el-table-column>
            <el-table-column
              prop="unitId"
              label="单位ID"
              align="center"
              min-width="100"
              v-if="showSystemColumns"
            ></el-table-column>

            <!-- 操作列 -->
            <el-table-column fixed="right" label="操作" align="center" min-width="180">
              <template slot-scope="scope">
                <!-- 确保row数据存在，默认isDeleted为0 -->
                <el-button
                  type="text"
                  size="small"
                  @click="openEditModal(scope.row)"
                  v-if="scope.row && (scope.row.isDeleted === 0 || scope.row.isDeleted === undefined)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleBatchOperation('delete', [scope.row.id])"
                  v-if="scope.row && (scope.row.isDeleted === 0 || scope.row.isDeleted === undefined)"
                >
                  删除
                </el-button>
<!--                <el-button-->
<!--                  type="text"-->
<!--                  size="small"-->
<!--                  @click="handleBatchOperation('delete', [scope.row.id])"-->
<!--                  v-if="scope.row && (scope.row.isDeleted === 0 || scope.row.isDeleted === undefined)"-->
<!--                >-->
<!--                  恢复-->
<!--                </el-button>-->
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <!-- 分页区域 -->
      <el-row v-if="total > 0">
        <el-col :span="24" style="margin-top: 20px" align="center">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :page-size="queryParams.pageSize"
            :total="total"
            :current-page="queryParams.pageNum"
            @current-change="getPageByPageNum"
            @size-change="handleSizeChange"
            :page-sizes="[10, 20, 50, 100]"
          ></el-pagination>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :span="24" style="margin-top: 20px; text-align: center; color: #999;">
          暂无数据
        </el-col>
      </el-row>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑合格证信息"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" :model="editObjects" :rules="editRules" label-width="100px">
        <!-- 基本信息 -->
        <el-form-item label="账号:">
          <el-input v-model="editObjects.account" disabled placeholder="账号信息"></el-input>
        </el-form-item>

        <el-form-item label="*生产主体:" prop="productionEntity">
          <el-input v-model="editObjects.productionEntity" placeholder="请输入生产主体"></el-input>
        </el-form-item>

        <el-form-item label="法人:">
          <el-input v-model="editObjects.legalPerson" placeholder="请输入法人信息"></el-input>
        </el-form-item>

        <el-form-item label="企业地址:">
          <el-input v-model="editObjects.companyAddress" placeholder="请输入企业地址"></el-input>
        </el-form-item>

        <el-form-item label="*生产地址:" prop="productionAddress">
          <el-input v-model="editObjects.productionAddress" placeholder="请输入生产地址"></el-input>
        </el-form-item>

        <!-- 产品信息 -->
        <el-form-item label="*产品名称:" prop="productName">
          <el-input v-model="editObjects.productName" placeholder="请输入产品名称"></el-input>
        </el-form-item>

        <el-form-item label="*产品重量:" prop="quantity">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="editObjects.quantity" type="number" placeholder="请输入数量"></el-input>
            </el-col>
            <el-col :span="8">
              <el-select v-model="editObjects.unit" placeholder="选择单位">
                <el-option label="公斤" value="公斤"></el-option>
                <el-option label="吨" value="吨"></el-option>
                <el-option label="个" value="个"></el-option>
                <el-option label="件" value="件"></el-option>
                <el-option label="箱" value="箱"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="合格方式:">
          <el-select v-model="editObjects.qualifiedMethod" placeholder="请选择合格方式">
<!--            <el-option label="自检承诺合格" value="自检承诺合格"></el-option>-->
            <el-option label="委托检验" value="委托检验"></el-option>
            <el-option label="监督抽检" value="监督抽检"></el-option>
          </el-select>
        </el-form-item>

        <!-- 时间与编号信息 -->
        <el-form-item label="开具时间:">
          <el-date-picker
            v-model="editObjects.issueDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开具时间"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="合格证编号:">
          <el-input v-model="editObjects.certificateNo" disabled placeholder="系统自动生成"></el-input>
        </el-form-item>

        <el-form-item label="打印次数:">
          <el-input v-model="editObjects.printCount" type="number" min="0" placeholder="请输入打印次数"></el-input>
        </el-form-item>

        <!-- 其他系统字段 -->
<!--        <el-form-item label="数据来源:">-->
<!--          <el-select v-model="editObjects.dataSource" placeholder="请选择数据来源">-->
<!--            <el-option label="平台录入" value="平台录入"></el-option>-->
<!--            <el-option label="API导入" value="API导入"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="是否删除:">-->
<!--          <el-select v-model="editObjects.isDeleted" placeholder="请选择状态">-->
<!--            <el-option label="未删除" value="0"></el-option>-->
<!--            <el-option label="已删除" value="1"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <!-- 系统字段（只读） -->
<!--        <el-form-item label="创建时间:">-->
<!--          <el-input v-model="editObjects.createTime" disabled></el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="更新时间:">-->
<!--          <el-input v-model="editObjects.updateTime" disabled></el-input>-->
<!--        </el-form-item>-->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitData">确定</el-button>
      </div>
    </el-dialog>


    <!-- 批量操作弹窗 -->
    <el-dialog
      title="确认操作"
      :visible.sync="confirmModalVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <p v-html="confirmModalContent"></p>

      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmModalVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmBatchOperation" v-if="confirmModalType === 'delete'">删除</el-button>
<!--        <el-button type="primary" @click="confirmBatchOperation" v-if="confirmModalType === 'restore'">恢复</el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入API接口
import { deleteCertificate, listCertificate, updateCertificate } from "@/api/njt/certificate/print/index.js";
// 导入行政区划数据（实际项目中可从API获取）
import { areaData } from '@/api/njt/certificate/print/area-data.js';
import { Message } from 'element-ui';
export default {
  name: 'CertificatePrintList',
  data() {
    return {
      // 查询参数（与实体类对应）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        account: '',
        productionEntity: '',
        productName: '',
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        townCode: '',
        inspectionOrg: '',
        qualifiedMethod: '',
        certificateNo: '',
        dataSource: '',
        isDeleted: undefined,
        // 日期范围查询参数
        startTime: '',
        endTime: '',
        province: '',
        city: '',
        district: '',
        town: '',
      },
      // 日期选择器绑定值
      dateRange: [],
      // 省份列表数据
      provinceList: [],
      // 城市数据映射 {provinceCode: [cities]}
      cityData: {},
      // 区县数据映射 {cityCode: [districts]}
      districtData: {},
      // 乡镇数据映射 {districtCode: [towns]}
      townData: {},
      // 查询表单用的城市和区县数据
      queryCities: [],
      queryDistricts: [],
      queryTowns: [],
      // 编辑弹窗用的城市和区县数据
      editCities: [],
      editDistricts: [],
      editTowns: [],
      // 表格数据
      tableData: [],
      // 分页总数
      total: 0,
      // 展开/收起状态
      isExpanded: false,
      currentRowIndex: 0, // 用于控制查询条件行显示
      // 选中的ID
      selectedIds: [],
      selectedCount: 0,
      // 编辑弹窗
      dialogVisible: false,
      editObjects: {
        // 实体类所有字段
        id: '',
        account: '',
        productionEntity: '',
        legalPerson: '',
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        townCode: '',
        province: '',  // 存储名称用于显示
        city: '',
        district: '',
        town: '',
        companyAddress: '',
        productionAddress: '',
        productName: '',
        quantity: '',
        unit: '',
        qualifiedMethod: '',
        inspectionOrg: '',
        reportUrl: '',
        reportName: '',
        issueDate: '',
        certificateNo: '',
        printCount: 0,
        scanCount: 0,
        dataSource: '',
        isDeleted: 0,
        createTime: '',
        updateTime: '',
        createUserId: '',
        unitId: ''
      },
      // 编辑表单验证规则
      editRules: {
        productionEntity: [
          { required: true, message: '请输入生产主体', trigger: 'blur' }
        ],
        productionAddress: [
          { required: true, message: '请输入生产地址', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入产品重量', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ]
      },
      // 确认弹窗（删除/恢复）
      confirmModalVisible: false,
      confirmModalType: 'delete', // delete/restore
      confirmModalContent: '',
      // 当前用户角色（实际项目中应从登录状态获取）
      currentUser: {},
      // 显示控制
      showAccount: true,
      showEntityName: true,
      showProvince: true,
      showCity: true,
      showDistrict: true,
      showTown: true,
      isRegularUser: false,
      // 系统字段显示控制（仅管理员可见）
      showSystemColumns: false,
      // 表格加载状态
      tableLoading: false,
      // 临时存储操作的ID，避免覆盖用户选择
      operationIds: []
    };
  },
  async created() {
    // 获取用户信息（实际项目中应从登录状态获取）
    await this.getUserInfo();
    // 加载省市区数据
    await this.loadAreaData();
    // 调整查询条件显示
    this.adjustQueryConditionsByRole();
    // 获取列表数据
    this.getPage();
  },
  methods: {

    confirmBatchOperation() {
      if (this.confirmModalType === 'delete') {
        // 检查operationIds是否存在
        if (!this.operationIds || this.operationIds.length === 0) {
          this.$message.warning('请选择要删除的记录');
          return;
        }

        // 根据后端接口要求调整参数格式：
        // 若后端支持批量删除（接收数组）：
        deleteCertificate(this.operationIds)
          .then(response => {
            this.$message.success('删除成功');
            this.confirmModalVisible = false;
            this.getPage(); // 重新加载列表
            this.clearSelected(); // 清空选择
          })
          .catch(error => {
            console.error('删除接口调用失败', error);
            this.$message.error('删除失败，请重试');
          });

        // 若后端只支持单个删除（循环调用）：
        // Promise.all(this.operationIds.map(id => deleteCertificate(id)))
        //   .then(() => {
        //     this.$message.success('删除成功');
        //     this.confirmModalVisible = false;
        //     this.getPage();
        //     this.clearSelected();
        //   })
        //   .catch(error => {
        //     console.error('删除接口调用失败', error);
        //     this.$message.error('删除失败，请重试');
        //   });
      }
    },
    // 获取用户信息（模拟）
    async getUserInfo() {
      // 实际项目中应该从接口获取
      this.currentUser = {
        role: 'admin' // admin/supervisor/user
      };
      this.showSystemColumns = this.currentUser.role === 'admin';
    },

    // 加载省市区数据（从areaData导入）
    async loadAreaData() {
      try {
        // 使用导入的areaData作为行政区划数据源
        this.provinceList = areaData || [];

        // 构建城市、区县、乡镇数据映射
        this.cityData = {};
        this.districtData = {};
        this.townData = {};

        // 遍历省份数据
        this.provinceList.forEach(province => {
          if (province.children && province.children.length) {
            // 存储城市数据
            this.cityData[province.code] = province.children;

            // 遍历城市数据
            province.children.forEach(city => {
              if (city.children && city.children.length) {
                // 存储区县数据
                this.districtData[city.code] = city.children;

                // 遍历区县数据
                city.children.forEach(district => {
                  if (district.children && district.children.length) {
                    // 存储乡镇数据
                    this.townData[district.code] = district.children;
                  }
                });
              }
            });
          }
        });

        console.log('行政区划数据加载成功');
      } catch (error) {
        console.error('加载行政区划数据失败:', error);
        this.$message.error('加载地区数据失败，请刷新页面重试');
      }
    },

    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val && val.length === 2) {
        this.queryParams.startTime = this.formatDate(val[0]);
        this.queryParams.endTime = this.formatDate(val[1], true);
      } else {
        this.queryParams.startTime = '';
        this.queryParams.endTime = '';
      }
    },

    // 省份选择变化（区分查询和编辑场景）
    onProvinceChange(isEdit) {
      // 获取当前选中的code（区分编辑/查询场景）
      const provinceCode = isEdit ? this.editObjects.provinceCode : this.queryParams.provinceCode;
      const targetCities = isEdit ? 'editCities' : 'queryCities';
      const targetDistricts = isEdit ? 'editDistricts' : 'queryDistricts';
      const targetTowns = isEdit ? 'editTowns' : 'queryTowns';

      // 清空下级选择
      this[targetCities] = [];
      this[targetDistricts] = [];
      this[targetTowns] = [];

      // 根据code找到对应的省份名称
      const province = this.provinceList.find(item => item.code === provinceCode);
      const provinceName = province ? province.name : '';

      if (isEdit) {
        // 编辑场景：给编辑对象赋值名称
        this.editObjects.province = provinceName;  // 存储名称到editObjects（用于编辑时回显）
        this.editObjects.cityCode = '';
        this.editObjects.city = '';
        this.editObjects.districtCode = '';
        this.editObjects.district = '';
        this.editObjects.townCode = '';
        this.editObjects.town = '';
      } else {
        // 查询场景：给查询参数赋值名称（关键！后端需要这个名称）
        this.queryParams.province = provinceName;  // 传递名称给后端
        this.queryParams.cityCode = '';
        this.queryParams.city = '';
        this.queryParams.districtCode = '';
        this.queryParams.district = '';
        this.queryParams.townCode = '';
        this.queryParams.town = '';
      }

      // 加载对应城市数据（原有逻辑保留）
      if (provinceCode) {
        this[targetCities] = this.cityData[provinceCode] || [];
        if (!this[targetCities].length) {
          this.$message.warning(`${provinceName || '选中省份'}暂未获取到城市数据`);
        }
      }
    },

    // 城市选择变化（区分查询和编辑场景）
    onCityChange(isEdit) {
      const cityCode = isEdit ? this.editObjects.cityCode : this.queryParams.cityCode;
      const provinceCode = isEdit ? this.editObjects.provinceCode : this.queryParams.provinceCode;
      const targetDistricts = isEdit ? 'editDistricts' : 'queryDistricts';
      const targetTowns = isEdit ? 'editTowns' : 'queryTowns';

      // 清空下级
      this[targetDistricts] = [];
      this[targetTowns] = [];

      // 根据code找城市名称
      const cities = this.cityData[provinceCode] || [];
      const city = cities.find(item => item.code === cityCode);
      const cityName = city ? city.name : '';

      if (isEdit) {
        this.editObjects.city = cityName;  // 编辑场景赋值名称
        this.editObjects.districtCode = '';
        this.editObjects.district = '';
        this.editObjects.townCode = '';
        this.editObjects.town = '';
      } else {
        this.queryParams.city = cityName;  // 查询场景传递名称给后端
        this.queryParams.districtCode = '';
        this.queryParams.district = '';
        this.queryParams.townCode = '';
        this.queryParams.town = '';
      }

      // 加载区县数据（原有逻辑保留）
      if (cityCode) {
        this[targetDistricts] = this.districtData[cityCode] || [];
      }
    },

    // 区县选择变化（区分查询和编辑场景）
    onDistrictChange(isEdit) {
      const districtCode = isEdit ? this.editObjects.districtCode : this.queryParams.districtCode;
      const cityCode = isEdit ? this.editObjects.cityCode : this.queryParams.cityCode;
      const targetTowns = isEdit ? 'editTowns' : 'queryTowns';

      // 清空下级选择
      this[targetTowns] = [];

      if (isEdit) {
        // 编辑场景逻辑（保持不变）
        this.editObjects.townCode = '';
        this.editObjects.town = '';
        const districts = this.districtData[cityCode] || [];
        const district = districts.find(item => item.code === districtCode);
        this.editObjects.district = district ? district.name : '';
      } else {
        // 查询场景：新增区名称赋值
        const districts = this.districtData[cityCode] || [];
        const district = districts.find(item => item.code === districtCode);
        this.queryParams.district = district ? district.name : ''; // 将区名称传给后端
        this.queryParams.townCode = '';
        this.queryParams.town = ''; // 清空镇参数
      }

      // 加载乡镇数据（保持不变）
      if (districtCode) {
        this[targetTowns] = this.townData[districtCode] || [];
        if (!this[targetTowns].length) {
          const districts = this.districtData[cityCode] || [];
          const district = districts.find(item => item.code === districtCode);
          const districtName = district ? district.name : '选中区县';
          this.$message.warning(`${districtName}暂未获取到乡镇数据`);
        }
      }
    },
    onTownChange(isEdit) {
      const townCode = isEdit ? this.editObjects.townCode : this.queryParams.townCode;
      const districtCode = isEdit ? this.editObjects.districtCode : this.queryParams.districtCode;

      if (isEdit) {
        // 编辑场景：赋值镇名称
        const towns = this.townData[districtCode] || [];
        const town = towns.find(item => item.code === townCode);
        this.editObjects.town = town ? town.name : '';
      } else {
        // 查询场景：将镇名称传给后端
        const towns = this.townData[districtCode] || [];
        const town = towns.find(item => item.code === townCode);
        this.queryParams.town = town ? town.name : '';
      }
    },

    // 切换展开/收起
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    },

    // 分页查询
    getPage() {
      this.tableLoading = true;
      const params = {...this.queryParams};
      console.log("查询参数：", params);
      listCertificate(params)
        .then(response => {
          this.tableLoading = false;
          // 检查响应结构
          if (!response || typeof response !== 'object') {
            this.$message.error('获取数据失败：响应格式异常');
            this.tableData = [];
            this.total = 0;
            return;
          }

          if (Array.isArray(response.rows) && typeof response.total === 'number') {
            this.tableData = response.rows;
            this.total = response.total;
          } else {
            this.tableData = [];
            this.total = 0;
            this.$message.warning('获取数据格式异常');
          }
        })
        .catch(error => {
          this.tableLoading = false;
          console.error('获取合格证列表失败:', error);
          // 更详细的错误信息
          if (error.response) {
            this.$message.error(`获取数据失败：${error.response.status} ${error.response.statusText}`);
          } else {
            this.$message.error('获取数据失败，请重试');
          }
        });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.searchForm) {
        this.$refs.searchForm.resetFields();
      }
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        account: '',
        productionEntity: '',
        productName: '',
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        townCode: '',
        inspectionOrg: '',
        qualifiedMethod: '',
        certificateNo: '',
        dataSource: '',
        isDeleted: undefined,
        startTime: '',
        endTime: ''
      };
      this.dateRange = [];
      this.queryCities = [];
      this.queryDistricts = [];
      this.queryTowns = [];
      this.clearSelected();
      this.getPage();
    },

    // 导出功能
    handleExport(){
      this.download('/nongjt/certificatePrint/export', {
        ...this.queryParams
      }, `合格证打印列表_${new Date().getTime()}.xlsx`);
    },

    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id);
      this.selectedCount = this.selectedIds.length;
    },

    // 清空选择
    clearSelected() {
      this.selectedIds = [];
      this.selectedCount = 0;
      if (this.$refs.certificateTable) {
        this.$refs.certificateTable.clearSelection();
      }
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getPage();
    },

    // 当前页变化
    getPageByPageNum(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },

    // 打开编辑弹窗
    openEditModal(rowData) {
      this.editObjects = JSON.parse(JSON.stringify(rowData));

      // 处理日期格式
      try {
        if (this.editObjects.issueDate) {
          const date = new Date(this.editObjects.issueDate);
          if (!isNaN(date.getTime())) {
            this.editObjects.issueDate = date;
          } else {
            this.editObjects.issueDate = '';
            this.$message.warning('日期格式无效，已重置');
          }
        }
      } catch (error) {
        this.editObjects.issueDate = '';
        this.$message.warning('日期格式解析失败，已重置');
      }

      // 初始化编辑弹窗的省市区县乡镇数据
      if (this.editObjects.provinceCode) {
        // 加载城市
        this.editCities = this.cityData[this.editObjects.provinceCode] || [];

        if (this.editObjects.cityCode) {
          // 加载区县
          this.editDistricts = this.districtData[this.editObjects.cityCode] || [];

          if (this.editObjects.districtCode) {
            // 加载乡镇
            this.editTowns = this.townData[this.editObjects.districtCode] || [];
          }
        }
      }

      this.dialogVisible = true;
    },

    // 保存编辑
    submitData() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          try {
            const formData = {
              ...this.editObjects,
              // 处理日期格式
              issueDate: this.editObjects.issueDate
                ? this.formatDate(this.editObjects.issueDate)
                : ''
            };

            updateCertificate(formData)
              .then(response => {
                this.getPage();
                this.$message.success(response.msg || "更新成功");
                this.dialogVisible = false;
              })
              .catch(error => {
                console.error('更新合格证信息失败:', error);
                this.$message.error(error.response?.data?.msg || '更新失败，请重试');
              });
          } catch (error) {
            console.error('提交数据处理失败:', error);
            this.$message.error('数据格式错误，请检查输入');
          }
        }
      });
    },

    // 格式化日期
    formatDate(date, isEndDate = false) {
      if (!date) return '';

      try {
        let dateObj;
        if (date instanceof Date) {
          dateObj = date;
        } else if (typeof date === 'string') {
          dateObj = new Date(date);
        } else {
          return '';
        }

        // 检查日期是否有效
        if (isNaN(dateObj.getTime())) return '';

        // 如果是结束日期，设置为当天的23:59:59
        if (isEndDate) {
          dateObj.setHours(23, 59, 59, 999);
        }

        // 手动格式化日期为yyyy-MM-dd HH:mm:ss
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const minutes = String(dateObj.getMinutes()).padStart(2, '0');
        const seconds = String(dateObj.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('日期格式化失败:', error);
        return '';
      }
    },

    // 表格日期格式化
    formatTableDate(row, column, cellValue) {
      if (!cellValue) return '';

      try {
        const date = new Date(cellValue);
        if (isNaN(date.getTime())) return cellValue;

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('表格日期格式化失败:', error);
        return cellValue;
      }
    },

    // 查看报告
    viewReport(reportUrl) {
      if (!reportUrl) {
        this.$message.warning('无报告地址');
        return;
      }

      try {
        // 简单验证URL格式
        new URL(reportUrl);
        window.open(reportUrl, '_blank');
      } catch (error) {
        this.$message.error('报告地址格式无效');
        console.error('无效的报告URL:', error);
      }
    },

    // 查看详情
    handleView(row) {
      this.$message.info(`查看ID为【${row.id}】的合格证详情`);
    },

    // 打印合格证
    printCertificate(id) {
      if (!id) return;
      this.$message.info(`开始打印ID为【${id}】的合格证`);
    },

    // 批量操作处理
    handleBatchOperation(type, singleId) {
      if (type === 'delete') {
        // 1. 确定要删除的ID列表（单个删除或批量删除）
        const deleteIds = singleId ? singleId : this.selectedIds;

        // 2. 关键修改：将ID数组包装为{ ids: [...] }格式（与后端实体类匹配）
        const deleteParams = { ids: deleteIds };

        // 3. 调用删除接口（确认接口方法为DELETE，参数为包装后的对象）
        this.$confirm('确定要删除选中的记录吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 假设删除接口为deleteCertificate（需确保接口封装正确）
          deleteCertificate(deleteParams).then(response => {
            this.$message.success(response.msg);
            this.getPage(); // 重新加载列表
            this.clearSelected(); // 清空选中状态
          }).catch(error => {
            this.$message.error('删除失败：' + (error.msg || error.message));
          });
        });
      }
    },

    // 表格行样式
    tableRowClassName({row}) {
      if (row.isDeleted === 1) {
        return 'row-deleted';
      }
      return '';
    },

    // 处理详情查看
    handleDetail(row) {
      this.$message.info(`查看ID为【${row.id}】的详细信息`);
    },

    // 根据用户角色调整查询条件显示
    adjustQueryConditionsByRole() {
      if (this.currentUser.role === 'supervisor') {
        this.showProvince = false;
        this.showCity = false;
        this.showDistrict = false;
      } else if (this.currentUser.role === 'user') {
        this.showAccount = false;
        this.showEntityName = false;
        this.showProvince = false;
        this.showCity = false;
        this.showDistrict = false;
        this.showTown = false;
        this.isRegularUser = true;
        this.showSystemColumns = false;
      }
    }
  }
};
</script>

<style scoped>
::v-deep .el-card__body {
  padding: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 15px;
}

::v-deep .el-row {
  margin-bottom: 10px;
}

::v-deep .el-table {
  font-size: 14px;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .row-deleted {
  background-color: #fafafa;
  color: #999;
}

::v-deep .row-deleted .el-tag {
  opacity: 0.6;
}

::v-deep .el-table .el-button--text {
  padding: 0 5px;
  /* 确保按钮始终可见 */
  display: inline-block !important;
}

::v-deep .el-dropdown-menu {
  min-width: 120px;
}

/* 修复操作列按钮可能被隐藏的问题 */
::v-deep .el-table__fixed-right {
  height: 100% !important;
}
</style>
